package com.binance.mbxgateway.web.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.HttpStatusCodeException;

import com.binance.assetservice.api.IProductApi;
import com.binance.assetservice.api.ISymbolRealtimeApi;
import com.binance.assetservice.vo.request.product.GetProductItemRequest;
import com.binance.assetservice.vo.request.symbolrealtime.GetClosePriceRequest;
import com.binance.assetservice.vo.response.symbolrealtime.GetClosePriceResponse;
import com.binance.master.error.BusinessException;
import com.binance.mbxgateway.web.service.IMatchboxRestService;
import com.binance.mbxgateway.web.service.IPriceService;
import com.binance.mbxgateway.web.utils.MatchboxReturnUtils;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class PriceServiceImpl extends BaseServiceImpl implements IPriceService {

    @Resource
    private IProductApi productApi;

    @Resource
    private ISymbolRealtimeApi symbolRealtimeApi;

    @Autowired
    private IMatchboxRestService matchboxRestService;


    @Override
    public Double getMbxPrice(String symbol) throws Exception {
        GetProductItemRequest body = new GetProductItemRequest();
        body.setSymbol(symbol);
        if (this.getAPIRequestResponse(this.productApi.getProductItem(this.newAPIRequest(body))) == null) {
            return 0D;
        }
        GetClosePriceRequest req = new GetClosePriceRequest();
        req.setSymbol(symbol);
        List<GetClosePriceResponse> list =
                this.getAPIRequestResponse(symbolRealtimeApi.getClose(this.newAPIRequest(req)));
        return CollectionUtils.isEmpty(list) ? 0d : list.get(0).getPrice().doubleValue();
    }

    @Override
    public String get24hrTicker(String symbol) throws Exception {
        try {
            return MatchboxReturnUtils.getMbxValue(this.matchboxRestService.get24hrTicker(symbol), String.class);
        } catch (HttpStatusCodeException e) {
            String errJson = e.getResponseBodyAsString();
            log.error("get24hrTicker is error:{},{}", errJson, e);
            throw new BusinessException(errJson);
        } catch (Exception e) {
            log.error("get24hrTicker exception: {}", e);
            throw e;
        }
    }

}
